﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using nRoute.Components;
using Orktane.Components;

namespace Orktane.Controls
{
    public partial class ConsoleWindow 
        : UserControl, IConsoleHost
    {
        public static readonly DependencyProperty ConsoleProperty =
           DependencyProperty.Register("Console", typeof(IConsole), typeof(ConsoleWindow),
           new PropertyMetadata(new Console()));

        public ConsoleWindow()
        {
            InitializeComponent();
            SetupConsole();
        }

#region IConsoleHost Members

        public IConsole Console
        {
            get { return (IConsole)GetValue(ConsoleProperty); }
        }

#endregion

#region Helpers

        private void SetupConsole()
        {
            // we set the viewmodel
            this.DataContext = this.Console;

            // we set two converters
            this.SetRelayConverter<ReadInputMode, bool>("InReadKeyModeConverterRelay",
                (im) => (im == ReadInputMode.ReadKey));
            this.SetRelayConverter<string, string>("NullToEmptyStringConverterRelay",
                (s) => s ?? string.Empty);

            // basic stuff
            //this.MouseLeftButtonUp += (s, e) => SetInputScrollFocus();
            this.KeyDown += (s, e) => SetInputScrollFocus();
            this.OutputTextBox.SizeChanged += (s, e) => SetInputScrollFocus();
        }

        private void SetInputScrollFocus()
        {
            if (Keyboard.Modifiers != ModifierKeys.None) return;

            // scroll
            this.ConsoleScrollViewer.ScrollToVerticalOffset(
                    this.ConsoleScrollViewer.ScrollableHeight + ConsoleScrollViewer.ViewportHeight);

            // focus
            if (this.InputTextBox.Visibility == System.Windows.Visibility.Visible)
            {
                if (!Object.ReferenceEquals(FocusManager.GetFocusedElement(), this.InputTextBox))
                    this.InputTextBox.Focus();
            }
            else
            {
                if (!Object.ReferenceEquals(FocusManager.GetFocusedElement(), this.DisabledInputTextBox))
                    this.DisabledInputTextBox.Focus();
            }
        }

#endregion

    }
}
